//
//  CodeInputView.swift
//  clreader
//
//  Created by colin on 2019/3/26.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

class CodeInputView: UIView {

    var text:String? {
        return self.textView.text
    }
    
    var completeHandle:((_ code:String)->Void)?
    
    private var codeCount = 6
    
    private lazy var textView = UITextView(frame: CGRect.zero)
    
    private var labels = [UILabel]()
    
    init(count:Int) {
        super.init(frame: CGRect.zero)
        self.codeCount = count
        self.initViews()
    }
    
    private func initViews() {
        
        self.textView.do {
            $0.tintColor = UIColor.clear
            $0.backgroundColor = UIColor.clear
            $0.textColor = UIColor.clear
            $0.delegate = self
            $0.keyboardType = .numberPad
        }
        self.addSubview(self.textView)
        self.textView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let itemSize = CGSize(width: 36.0, height: 36.0)
        let distance:CGFloat = 5.0
        
        var pre:UIView?
        for index in 0 ..< self.codeCount {
            
            let item = UIView().then {
                $0.backgroundColor = UIColor.clear
                $0.isUserInteractionEnabled = false
                
                let labelCode = UILabel().then {
                    $0.textAlignment = .center
                    $0.textColor = UIColor(hex: "343434")
                    $0.font = UIFont.systemFont(ofSize: 34.0, weight: .light)
                }
                $0.addSubview(labelCode)
                labelCode.snp.makeConstraints({ (make) in
                    make.center.equalToSuperview()
                })
                self.labels.append(labelCode)
                
                let lineView = UIView().then {
                    $0.backgroundColor = UIColor(hex: "343434")
                }
                $0.addSubview(lineView)
                lineView.snp.makeConstraints({ (make) in
                    make.left.right.bottom.equalToSuperview()
                    make.height.equalTo(1.0)
                })
                
            }
            self.addSubview(item)
            item.snp.makeConstraints { (make) in
                if let pre_ = pre {
                    make.left.equalTo(pre_.snp.right).offset(distance)
                    make.width.equalTo(pre_.snp.width)
                    make.top.equalTo(pre_.snp.top)
                    make.bottom.equalTo(pre_.snp.bottom)
                } else {
                    make.left.equalToSuperview()
                    make.top.equalToSuperview()
                    make.bottom.equalToSuperview()
                    make.size.equalTo(itemSize)
                }
                
                if index == self.codeCount - 1 {
                    make.right.equalToSuperview()
                }
            }
            
            pre = item
        }
    }
    
    //开始编辑
    func beginEdit() {
        self.textView.becomeFirstResponder()
    }
    
    //结束编辑
    func endEdit() {
        self.textView.resignFirstResponder()
    }
    
    private func opacityAnimation() -> CABasicAnimation {
        let opacityAnimation = CABasicAnimation(keyPath: "opacity")
        opacityAnimation.fromValue = 1.0
        opacityAnimation.toValue = 0
        opacityAnimation.duration = 0.9
        opacityAnimation.repeatCount = Float.greatestFiniteMagnitude
        opacityAnimation.isRemovedOnCompletion = true
        opacityAnimation.fillMode = .forwards
        opacityAnimation.timingFunction = CAMediaTimingFunction(name: .easeIn)
        return opacityAnimation
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension CodeInputView : UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        guard let verStr = textView.text else { return }
        
        if verStr.count > self.codeCount {
            textView.text = String(verStr.prefix(self.codeCount))
        }
        
        //大于等于最大值时, 结束编辑
        if verStr.count >= self.codeCount {
            self.endEdit()
            self.completeHandle?(verStr)
        }
        
        for index in 0 ..< self.codeCount {
            let bgLabel = self.labels[index]
            if index < verStr.count {
                let startIndex = verStr.index(verStr.startIndex, offsetBy: index)
                let endIndex =  verStr.index(verStr.startIndex, offsetBy: index)
                bgLabel.text = String(verStr[startIndex ... endIndex])
            } else {
                bgLabel.text = ""
            }

        }

    }

}
